package com.chenxingnet.controller;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.chenxingnet.tools.MD5Tools;

import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.chenxingnet.dto.Department;
import com.chenxingnet.dto.Role;
import com.chenxingnet.dto.UserDepartment;
import com.chenxingnet.dto.Usercontrol;
import com.chenxingnet.service.DepartmentService;
import com.chenxingnet.service.IRoleService;
import com.chenxingnet.service.ManagerService;
import com.chenxingnet.service.UserDeptService;

@Controller
@RequestMapping("/tuser")
public class ManagerController {
	
	@Resource
	private ManagerService managerService;
	
	@Resource
	private DepartmentService  departmentService;
	@Resource
	private UserDeptService userDeptService;
	@Resource 
	IRoleService  roleService;
	
	@RequestMapping("/userLogin")
	public void userLogin(HttpServletRequest request,Model model,HttpServletResponse httpServletResponse){
		JSONObject json = new JSONObject();
		System.out.println("userLogin");
		
		try {
			
			httpServletResponse.setContentType("application/json;charset=UTF-8");
			String  uAccount=request.getParameter("username");
			String  uPassword=request.getParameter("pwd");
			Usercontrol user = managerService.userLogin(uAccount,MD5Tools.MD5(uPassword) );
			if(user!=null&&user.getUaccount()!=null&&!user.getUaccount().equals("")){
				json.put("re", "1");
				json.put("data", user);
			}else{
				json.put("re", "0");
				json.put("msg", "登录失败，用户名或者密码错误。");
			}
			
			httpServletResponse.getWriter().print(json);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		
		
	}
	
	/**
	* @Title: mobile_login 
	* @Description: 登录方法POST请求
	* @param @param username  用户名
	* @param @param userpwd   密码
	*{username:'admin',password:'admin'}
	 */
	@RequestMapping("/mobile_login")
	public void mobile_login(HttpServletRequest request,HttpServletResponse response){
		try {
				response.setHeader("Access-Control-Allow-Origin", "*");
				response.setContentType("application/json;charset=utf-8");
				String   username  = 	request.getParameter("username");
				String   password  = 	request.getParameter("password");
				Usercontrol user = managerService.userLogin(username,MD5Tools.MD5(password) );
				JSONObject returnJson = new JSONObject();
				if (user != null){
					Role   role = managerService.selectByRid(user.getRoleid());
					UserDepartment	 userDept = userDeptService.selectByUid(user.getUid());
					returnJson.put("falg","true");
					returnJson.put("userdep",userDept);
					returnJson.put("username", username);
					returnJson.put("role",role);
					returnJson.put("uname","admin");
					returnJson.put("user",user);
					returnJson.put("result", "1");
					returnJson.put("password", password);
				}else{
					returnJson.put("falg","true");
					returnJson.put("result", "0");
				}
				response.getWriter().print(returnJson.toString());
		} catch (Exception e) {  e.printStackTrace();  }
	}

	
	
	

	//  用户名重复检测    ajax
	@RequestMapping("/userRenameTest")
	@ResponseBody
	public Map<String,Object> userRenameTest(HttpServletRequest request,Model model,  HttpServletResponse httpServletResponse,String  thisusername){
		httpServletResponse.setCharacterEncoding("UTF-8");
		String   username=request.getParameter("user");
		System.out.println(username+"username");
		List<Usercontrol>  users=   managerService.userTest(username);
		Map<String, Object> result=new HashMap<String, Object>();
		if(users.size()==0){
				result.put("result", "0");
		}else{
			result.put("result", "1");
		}
		return  result;
	}
	
	
	
	/**
	 * 用户增加-发送账号-跳转
	 */
	@RequestMapping("/userAddSkip")
	public String userAddSkip(HttpServletRequest request,HttpSession session,Model model,HttpServletResponse response){
		try {
			Integer deptid = Integer.valueOf(request.getParameter("deptid"));
			if(deptid != null){
				model.addAttribute("deptid", deptid);
			}
		} catch (Exception e) {
			
		}
		
		System.out.println("userAddSkip");
		List<Department> deps=    departmentService.showDept();
		for (int i = 0; i < deps.size(); i++) {
			if(deps.get(i).getDeptname().equals("全部")){
				deps.remove(i);
			}
		}
		
		List<Role> rs=	roleService.getAllRoles();
		
		try {
			model.addAttribute("dept", deps);
			if(request.getAttribute("result").equals("对不起，您无此操作权限。")){
				model.addAttribute("action", "对不起，您无此操作权限。");
				
				return "guanli";
			}
		} catch (Exception e) {
			model.addAttribute("deps", deps);
			model.addAttribute("rs", rs);
			return "account_send";
		}
		
		model.addAttribute("deps", deps);
		model.addAttribute("rs", rs);
		return "account_send";
	}
	
	
	/**
	 * 用户增加-发送账号
	 */
	@RequestMapping("/userAdd")
	public String userAdd(HttpServletRequest request,HttpSession session,Model model, HttpServletResponse response){
		
		try {
			Integer deptid = Integer.valueOf(request.getParameter("deptid"));
			if(deptid != null){
				model.addAttribute("deptid", deptid);
			}
		} catch (Exception e) {
			
		}
		
		List<Department> deps1=    departmentService.showDept();
		
		String  roleid=request.getParameter("permissionsRadioOptions");
		String  realname=request.getParameter("realname");
		String  username=request.getParameter("username");
		String  pwd=request.getParameter("pwd");
		String  depid=request.getParameter("inlineRadioOptions");
		if(roleid.equals("4")){
			depid="1";
		}
		
		Usercontrol   usercontrol=new  Usercontrol();
		usercontrol.setUname(realname);
		usercontrol.setUreportstart("1");
		usercontrol.setUpubdate(new   Date());
		usercontrol.setRoleid(Integer.parseInt(roleid));
		usercontrol.setUaccount(username);
		usercontrol.setUpassword(MD5Tools.MD5(pwd));
		int   res=	managerService.userAdd(usercontrol,Integer.parseInt(depid));
		model.addAttribute("res", res);
		List<Department> deps=    departmentService.showDept();
		List<Role> rs=	roleService.getAllRoles();
		model.addAttribute("deps", deps);
		model.addAttribute("rs", rs);
		model.addAttribute("result", "用户添加成功");
		return "redirect:/back/guanli";
	}
	
	/**
	* @Title: /tuser/mobile_userAdd 
	*移动端新增用户信息
	 */
	@RequestMapping("/mobile_userAdd")
	public void mobile_userAdd(HttpServletRequest request,HttpSession session,Model model, HttpServletResponse response){
		
		try {
			
			response.setHeader("Access-Control-Allow-Origin", "*");
			response.setContentType("application/json;charset=utf-8");
			JSONObject returnJson = new JSONObject();
			returnJson.put("falg","true");
			
			try {
				Integer deptid = Integer.valueOf(request.getParameter("deptid"));
				if(deptid != null){
					returnJson.put("deptid", deptid);
				}
			} catch (Exception e) {
				
			}
			
			List<Department> deps1=    departmentService.showDept();
			
			String  roleid=request.getParameter("permissionsRadioOptions");
			String  realname=request.getParameter("realname");
			String  username=request.getParameter("username");
			String  pwd=request.getParameter("pwd");
			String  depid=request.getParameter("inlineRadioOptions");
			if(roleid.equals("4")){
				depid="1";
			}
			
			Usercontrol   usercontrol=new  Usercontrol();
			usercontrol.setUname(realname);
			usercontrol.setUreportstart("1");
			usercontrol.setUpubdate(new   Date());
			usercontrol.setRoleid(Integer.parseInt(roleid));
			usercontrol.setUaccount(username);
			usercontrol.setUpassword(MD5Tools.MD5(pwd));
			int   res=	managerService.userAdd(usercontrol,Integer.parseInt(depid));
			returnJson.put("result", res);
			List<Department> deps=    departmentService.showDept();
			List<Role> rs=	roleService.getAllRoles();
		
			returnJson.put("deps", deps);
			returnJson.put("rs", rs);
			returnJson.put("sult", "用户添加成功");
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
	}
	
	
	/**
	 * 用户增加-发送账号-跳转
	 */
	@RequestMapping("/guanliSkip")
	public String guanliSkip(HttpServletRequest request,HttpSession session,Model model){
		try {
			Integer deptid = Integer.valueOf(request.getParameter("deptid"));
			if(deptid != null){
				model.addAttribute("deptid", deptid);
			}
		} catch (Exception e) {
			
		}
		return "guanli";
	}
	/**
	 * 转至修改密码页面
	 * @return
	 */
	@RequestMapping("/pwdjsp")
	public String pwdjsp(HttpServletRequest request,Model model){
		try {
			Integer deptid = Integer.valueOf(request.getParameter("deptid"));
			if(deptid != null){
				model.addAttribute("deptid", deptid);
			}
		} catch (Exception e) {
			
		}
		return "password";
	}
	/**
	 * 修改用户密码
	 * @return
	 */
	@RequestMapping("/updatePwd")
	public String updatePwd(HttpServletRequest request,Model model){
		try {
			Integer deptid = Integer.valueOf(request.getParameter("deptid"));
			if(deptid != null){
				model.addAttribute("deptid", deptid);
			}
		} catch (Exception e) {
			
		}
		String uaccount = request.getParameter("uaccount");
		String password = request.getParameter("pwd1");
		Usercontrol user = managerService.userLogin(uaccount, MD5Tools.MD5(password));
		if(user==null){
			model.addAttribute("result", "修改失败，原密码错误");
			return "password";
		}
		String pwd = request.getParameter("upassword");
		user.setUpassword(MD5Tools.MD5(pwd));
		managerService.updatePwd(user);
		model.addAttribute("result", "密码修改成功，请重新登录");
		return "index";
	}
	/**
	* @Title: /tuser/mobile_updatePwd
	*移动端修改用户密码
	 */
	@RequestMapping("/mobile_updatePwd")
	public void mobile_updatePwd(HttpServletRequest request,Model model,HttpServletResponse response){
		try {
			
			response.setHeader("Access-Control-Allow-Origin", "*");
			response.setContentType("application/json;charset=utf-8");
			JSONObject returnJson = new JSONObject();
			returnJson.put("falg","true");
			try {
				Integer deptid = Integer.valueOf(request.getParameter("deptid"));
				if(deptid != null){
					returnJson.put("deptid", deptid);
				}
			} catch (Exception e) {
				
			}
			String uaccount = request.getParameter("uaccount");
			String password = request.getParameter("pwd1");
			Usercontrol user = managerService.userLogin(uaccount, MD5Tools.MD5(password));
			if(user==null){
				returnJson.put("sult", "修改失败，原密码错误");
			}
			String pwd = request.getParameter("upassword");
			user.setUpassword(MD5Tools.MD5(pwd));
			int resu = managerService.updatePwd(user);
			
			returnJson.put("result",resu);//返回修改结果。
			returnJson.put("sult", "密码修改成功，请重新登录");
			
			response.getWriter().print(returnJson.toString());
			
		} catch (Exception e) {
			e.printStackTrace();
			
		}
		
	}
	/**
	 * 分页查询用户信息
	 * @return
	 */
	@RequestMapping("/showUser")
	public String showUser(HttpServletRequest request, Model model){
		managerService.showUserByCount(request, model);
		return "addUser";
	}
	/**
	 * 删除用户信息
	 * @return
	 */
	@RequestMapping("/delUser")
	public String delUse(Integer uid){
		managerService.delUser(uid);
		return "redirect:/tuser/showUser?pageNow=1";
	}
	

}
